"use client";

import { useEffect, useState } from 'react';
import { useRouter } from "next/navigation";
import { ExitDialog } from '../dialog/dialog';

export const Header = ({ name }: { name: JSX.Element }) => {

    const [showDialog, setShowDialog] = useState(false);
    const router = useRouter();

    const handleExitClick = () => {
        setShowDialog(true);
    };

    const handleClose = () => {
        setShowDialog(false);
    };

    const handleConfirm = () => {
        setShowDialog(false);

        router.push('/register/login');
    };

    const [color, setColor] = useState("");

    useEffect(() => {

        const fetchUrl = async () => {
            const res = await (await fetch('/api/color')).json();
            setColor(JSON.parse(res));
        }

        fetchUrl();
    }, []);

    return <>
        <div style={{ padding: '10px', backgroundColor: color || 'red', display: 'flex', justifyContent: 'center' }}>

            <h1 style={{ textAlign: 'center', flexGrow: 1 }}>View</h1>

            <div style={{ marginLeft: 'auto' }}>
                <span style={{marginRight: '10px'}}>{name}</span>

                <button onClick={handleExitClick} style={{  backgroundColor: '#00BCD4', padding: '2px 20px', borderRadius: '5px'}}>Logout</button>
            </div>

            <ExitDialog
                open={showDialog}
                onClose={handleClose}
                onConfirm={handleConfirm}
            />
        </div>
    </>
}
